using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using GriffinNav.GPS;

namespace GriffinNav.UI
{
    public class AppState
    {
        #region AppState.xml Document Format
        //  <configuration>
        //      <appState>
        //          <add key="LastMapOpened" value="" />
        //          <add key="LastLongitude" value="" />
        //          <add key="LastLatitude" value="" />
        //          <add key="LastDetailLevel" value="" />
        //      </appState>
        //  </configuration>
        #endregion

        private static Dictionary<string, string> mState;
        private static string mStatePath;

        static AppState()
        {
            try
            {
                // set the app settings file path
                mStatePath = Path.Combine(Global.AppPath, "AppState.xml");

                // check if the file exists
                if (!File.Exists(mStatePath))
                {
                    Cursor.Current = Cursors.WaitCursor;

                    // create a new settings file in the application root
                    createStateFile();
                }

                XmlDocument xml = new XmlDocument();

                // load the settings xml
                xml.Load(mStatePath);

                // get only application settings
                XmlNodeList nodes = xml.SelectSingleNode("//configuration/appState").ChildNodes;
                mState = new Dictionary<string, string>();

                // load application settings into collection
                foreach (XmlNode node in nodes)
                {
                    mState.Add(node.Attributes["key"].Value, node.Attributes["value"].Value);
                }
            }
            catch (Exception ex)
            {
                Global.ShowError("Error", ex.Message);
            }

            Cursor.Current = Cursors.Default;
        }

        public static string LastMapOpened
        {
            get
            {
                if (!mState.ContainsKey("LastMapOpened"))
                {
                    mState.Add("LastMapOpened", string.Empty);

                    return string.Empty;
                }

                return mState["LastMapOpened"];
            }
            set
            {
                mState["LastMapOpened"] = value;
            }
        }

        public static decimal LastLatitude
        {
            get
            {
                if (!mState.ContainsKey("LastLatitude"))
                {
                    mState.Add("LastLatitude", string.Empty);
                    return -1M;
                }

                if (!string.IsNullOrEmpty(mState["LastLatitude"]))
                {
                    return decimal.Parse(mState["LastLatitude"]);
                }

                return -1M;
            }
            set
            {
                mState["LastLatitude"] = value.ToString();
            }
        }

        public static decimal LastLongitude
        {
            get
            {
                if (!mState.ContainsKey("LastLongitude"))
                {
                    mState.Add("LastLongitude", string.Empty);
                    return -1M;
                }

                if (!string.IsNullOrEmpty(mState["LastLongitude"]))
                {
                    return decimal.Parse(mState["LastLongitude"]);
                }

                return -1M;
            }
            set
            {
                mState["LastLongitude"] = value.ToString();
            }
        }

        public static int LastDetailLevel
        {
            get
            {
                if (!mState.ContainsKey("LastDetailLevel"))
                {
                    mState.Add("LastDetailLevel", string.Empty);
                    return -1;
                }

                if (!string.IsNullOrEmpty(mState["LastDetailLevel"]))
                {
                    return int.Parse(mState["LastDetailLevel"]);
                }

                return -1;
            }
            set
            {
                mState["LastDetailLevel"] = value.ToString();
            }
        }

        public static void Save()
        {
            XmlWriter writer = null;

            try
            {
                // create the xml file stream
                writer = XmlWriter.Create(mStatePath);
                writer.WriteStartDocument();

                //  <configuration>
                writer.WriteStartElement("configuration");

                //      <appSettings>
                writer.WriteStartElement("appState");

                foreach (KeyValuePair<string, string> setting in mState)
                {
                    writer.WriteStartElement("add");
                    writer.WriteAttributeString("key", setting.Key);
                    writer.WriteAttributeString("value", setting.Value);
                    writer.WriteEndElement();
                }

                //      </appState>
                writer.WriteEndElement();

                //  </configuration>
                writer.WriteEndElement();

                writer.WriteEndDocument();

                writer.Close();
                writer = null;
            }
            catch
            {
                if (writer != null)
                {
                    writer.Close();
                }

                Global.ShowError("Error", "Error saving application state.");
            }
        }

        private static void createStateFile()
        {
            XmlWriter writer = null;

            try
            {
                // create the xml file stream
                writer = XmlWriter.Create(mStatePath);
                writer.WriteStartDocument();

                //  <configuration>
                writer.WriteStartElement("configuration");

                //      <appState>
                writer.WriteStartElement("appState");

                //          <add key="LastMapOpened" value="" />
                writer.WriteStartElement("add");
                writer.WriteAttributeString("key", "LastMapOpened");
                writer.WriteAttributeString("value", string.Empty);
                writer.WriteEndElement();

                //          <add key="LastLongitude" value="" />
                writer.WriteStartElement("add");
                writer.WriteAttributeString("key", "LastLongitude");
                writer.WriteAttributeString("value", string.Empty);
                writer.WriteEndElement();

                //          <add key="LastLatitude" value="" />
                writer.WriteStartElement("add");
                writer.WriteAttributeString("key", "LastLatitude");
                writer.WriteAttributeString("value", string.Empty);
                writer.WriteEndElement();

                //          <add key="LastDetailLevel" value="" />
                writer.WriteStartElement("add");
                writer.WriteAttributeString("key", "LastDetailLevel");
                writer.WriteAttributeString("value", string.Empty);
                writer.WriteEndElement();

                //  </configuration>
                writer.WriteEndElement();

                writer.WriteEndDocument();

                writer.Close();
                writer = null;
            }
            catch
            {
                if (writer != null)
                {
                    writer.Close();
                }

                Global.ShowError("Error", "Error creating application state file.");
            }
        }
    }
}